import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../../core/repository/default_api.dart';
import '../../../core/controllers/ring_controller.dart';

/// 创建新群组页面
class CreateGroupPage extends StatefulWidget {
  const CreateGroupPage({super.key});

  @override
  State<CreateGroupPage> createState() => _CreateGroupPageState();
}

class _CreateGroupPageState extends State<CreateGroupPage> {
  final _api = DefaultApi();
  final groupNameController = TextEditingController();
  final inviteCodeController = TextEditingController();
  final isCreating = false.obs;

  @override
  void dispose() {
    groupNameController.dispose();
    inviteCodeController.dispose();
    super.dispose();
  }

  /// 发送邀请
  void sendInvite() {
    final inviteCode = inviteCodeController.text.trim();
    if (inviteCode.isEmpty) {
      Toast.show('请输入手机号或邮箱');
      return;
    }
  }

  /// 创建群组
  Future<void> createGroup() async {
    final groupName = groupNameController.text.trim();
    final inviteCode = inviteCodeController.text.trim();

    if (groupName.isEmpty) {
      Toast.show('请输入群组名称');
      return;
    }

    try {
      isCreating.value = true;

      // 1. 先获取群组码
      final codeResponse = await _api.queryGroupCodeGet();
      String? groupCode;

      if (codeResponse != null && codeResponse['code'] == 200) {
        // 从 msg 字段获取群组码
        groupCode = codeResponse['msg']?.toString();
      }

      if (groupCode == null || groupCode.isEmpty) {
        Toast.show('获取群组码失败');
        return;
      }

      // 2. 获取设备SN
      final ringController = Get.find<RingController>();
      final deviceSn = ringController.connectedDevice?.address ?? '';

      // 3. 创建群组，传入获取到的群组码
      final response = await _api.addGroupPost(
        deviceSn: deviceSn,
        groupName: groupName,
        groupCode: groupCode,
        remark: '',
      );

      if (response != null && response['code'] == 200) {
        Toast.show('创建成功');

        // 如果填写了邀请信息，自动发送邀请
        if (inviteCode.isNotEmpty) {
          await _sendInviteToMember(inviteCode, groupCode);
        }

        Get.back(result: true); // 返回并刷新列表
      } else {
        Toast.show('创建失败');
      }
    } catch (e) {
      Toast.show('创建失败: $e');
    } finally {
      isCreating.value = false;
    }
  }

  /// 发送邀请给成员
  Future<void> _sendInviteToMember(String inviteInfo, String groupCode) async {
    try {
      final response = await _api.applyJoinGroupPost(
        applyInfo: inviteInfo,
        groupCode: groupCode,
        joinType: '1', // 1: 邀请加入, 2: 申请加入
      );

      if (response != null && response['code'] == 200) {
        Toast.show('邀请已发送');
      }else{
         Toast.show(response['msg']);
      }
    } catch (e) {
      print('发送邀请失败: $e');
      // 不影响创建群组的成功提示
    }
  }

  @override
  Widget build(BuildContext context) {
    return CreateGroupView(
      groupNameController: groupNameController,
      inviteCodeController: inviteCodeController,
      isCreating: isCreating,
      onSendInvite: sendInvite,
      onCreateGroup: createGroup,
    );
  }
}

/// 创建新群组视图
class CreateGroupView extends StatelessWidget {
  final TextEditingController groupNameController;
  final TextEditingController inviteCodeController;
  final RxBool isCreating;
  final VoidCallback onSendInvite;
  final VoidCallback onCreateGroup;

  const CreateGroupView({
    super.key,
    required this.groupNameController,
    required this.inviteCodeController,
    required this.isCreating,
    required this.onSendInvite,
    required this.onCreateGroup,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.white, size: 20.sp),
          onPressed: () => Get.back(),
        ),
        title: Text(
          '创建新群组',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        centerTitle: true,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(20.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 20.h),
                // 群组名称输入框
                _buildInputField(
                  controllerField: groupNameController,
                  hintText: '你的群组名称',
                ),
                SizedBox(height: 30.h),
                // 数据分享说明
                _buildDataSharingInfo(),
                SizedBox(height: 30.h),
                // 添加群组成员
                _buildAddMembersSection(),
                SizedBox(height: 60.h),
                // 创建群组按钮
                _buildCreateButton(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 输入框
  Widget _buildInputField({
    required TextEditingController controllerField,
    required String hintText,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 4.h),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: TextField(
        controller: controllerField,
        style: TextStyle(
          fontSize: 16.sp,
          color: Colors.white,
        ),
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(
            fontSize: 16.sp,
            color: Colors.grey[600],
          ),
          border: InputBorder.none,
        ),
      ),
    );
  }

  /// 数据分享说明
  Widget _buildDataSharingInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '数据分享',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        SizedBox(height: 12.h),
        Text(
          '家庭圈会将身体活力值、睡眠、能量平衡等进行数据化数据呈现，分享这三项数据让亲友及时了解身体状况',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[500],
            height: 1.5,
          ),
        ),
      ],
    );
  }

  /// 添加群组成员部分
  Widget _buildAddMembersSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              '添加群组成员',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
            SizedBox(width: 8.w),
            Text(
              '(选填)',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
        SizedBox(height: 16.h),
        // 邀请码输入
        Container(
          padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: Colors.grey[900],
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: inviteCodeController,
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.white,
                  ),
                  decoration: InputDecoration(
                    hintText: '通过手机/邮箱搜索',
                    hintStyle: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.grey[600],
                    ),
                    border: InputBorder.none,
                  ),
                ),
              ),
              GestureDetector(
                onTap: onSendInvite,
                child: Container(
                  padding:
                      EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
                  decoration: BoxDecoration(
                    color: Colors.grey[800],
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Text(
                    '邀请',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 12.h),
        Text(
          '通过邀请码加入亲人守护群组',
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  /// 创建群组按钮
  Widget _buildCreateButton() {
    return Obx(() => GestureDetector(
          onTap: isCreating.value ? null : onCreateGroup,
          child: Container(
            width: double.infinity,
            height: 50.h,
            decoration: BoxDecoration(
              color: isCreating.value ? Colors.grey[800] : Colors.grey[900],
              borderRadius: BorderRadius.circular(25.r),
              border: Border.all(
                color: Colors.grey[700]!,
                width: 1.w,
              ),
            ),
            child: Center(
              child: isCreating.value
                  ? SizedBox(
                      width: 20.sp,
                      height: 20.sp,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : Text(
                      '创建群组',
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
            ),
          ),
        ));
  }
}
